<template>
  <view class="add-page">
    <up-form label-width="240rpx" v-model="form">
      <view class="form-container">
        <up-form-item label="盘点单号" class="border-bottom">
          <up-input disabled border="none" v-model="form.inventory_code"/>
        </up-form-item>
        <up-form-item label="盘点单名称" class="border-bottom" required>
          <up-input border="none" v-model="form.inventory_name"/>
        </up-form-item>
        <up-form-item label="盘点人" @click="handlerInventoryUser" class="border-bottom" required>
          <view @click.self="handlerInventoryUser">
            <up-input
                placeholder="请选择"
                border="none"
                v-model="form.inventory_user"
            ></up-input>
          </view>
          <template #right>
            <up-icon name="arrow-right"></up-icon>
          </template>
        </up-form-item>
        <up-form-item label="全员盘点" class="border-bottom">
          <view class="w100">
            <up-switch class="mla" v-model="form.all"></up-switch>
          </view>
        </up-form-item>
        <up-form-item label="全位置盘点" class="border-bottom">
          <view class="w100">
            <up-switch class="mla" v-model="form.all_local"></up-switch>
          </view>
        </up-form-item>
        <up-form-item label="允许手动盘点" class="border-bottom">
          <view class="w100">
            <up-switch class="mla" v-model="form.manual"></up-switch>
          </view>
        </up-form-item>
<!--        <up-form-item label="开启盘盈" class="border-bottom">-->
<!--          <view class="w100">-->
<!--            <up-switch class="mla" v-model="form.open"></up-switch>-->
<!--          </view>-->
<!--        </up-form-item>-->
<!--        <up-form-item label="异常须处理并审核" class="border-bottom">-->
<!--          <view class="w100">-->
<!--            <up-switch class="mla" v-model="form.audit"></up-switch>-->
<!--          </view>-->
<!--        </up-form-item>-->
<!--        <up-form-item label="盘点须上传图片">-->
<!--          <view class="w100">-->
<!--            <up-switch class="mla" v-model="form.upload"></up-switch>-->
<!--          </view>-->
<!--        </up-form-item>-->
      </view>
      <view class="form-container">
        <up-form-item label="备注" label-position="top" label-width="80rpx">
          <up-textarea placeholder="要留下点什么吗" v-model="form.remark"></up-textarea>
        </up-form-item>
      </view>
      <view class="form-container">
        <span>盘点条件</span>
        <u-line/>
        <up-form-item :label="item.label" @click="item.click(item)" class="border-bottom"
                      v-for="(item, index) in pickerData" :key="index">
          <view @click.self="item.click(item)">
            <up-input
                placeholder="请选择"
                border="none"
                v-model="form[item.field]"
            ></up-input>
          </view>
          <template #right>
            <up-icon name="arrow-right"></up-icon>
          </template>
        </up-form-item>
        <up-form-item label="采购开始日期" class="border-bottom" @click="handlerDate('startDate')">
          <view @click.self="handlerDate('startDate')">
            <up-input
                placeholder="请选择"
                border="none"
                v-model="form.start_date"
            ></up-input>
          </view>
          <template #right>
            <up-icon name="arrow-right"></up-icon>
          </template>
        </up-form-item>
        <up-form-item label="采购结束日期" class="border-bottom" @click="handlerDate('endDate')">
          <view @click.self="handlerDate('endDate')">
            <up-input
                placeholder="请选择"
                border="none"
                v-model="form.end_date"
            ></up-input>
          </view>
          <template #right>
            <up-icon name="arrow-right"></up-icon>
          </template>
        </up-form-item>
      </view>
    </up-form>
    <view class="footer-container">
      <up-button plain @click="handlerCancel">取消</up-button>
      <up-button plain @click="handlerSave">提交</up-button>
    </view>
    <up-picker v-for="(item, index) in pickerData" :key="index"
               :show="item.show" title="请选择" @cancel="item.show = false"
               :columns="[filterList[item.columns]]" :closeOnClickOverlay="false"
               :keyName="item.key" @confirm="item.confirm($event, item)"/>
    <up-picker :show="showInventoryUser" title="请选择" @cancel="showInventoryUser = false"
               :columns="[filterList.assetAdminList]" :closeOnClickOverlay="false"
               keyName="text" @confirm="confirmInventoryUser"/>
    <up-calendar :show="dateFilter.startDate" monthNum="12" @confirm="confirmDate($event, 'startDate','start_date')"
                 :closeOnClickOverlay="false"
                 @close="dateFilter.startDate = false"/>
    <up-calendar :show="dateFilter.endDate" monthNum="12" @confirm="confirmDate($event, 'endDate','end_date')"
                 :closeOnClickOverlay="false"
                 @close="dateFilter.endDate = false"/>
  </view>
</template>

<script setup>

import {onMounted, reactive, ref} from "vue";
import request from "@/api/request";
import {generateUUID} from "@/utils";
import {onLoad} from "@dcloudio/uni-app";

onMounted(() => {
  requestData()
})

onLoad(async (options) => {
  const item = JSON.parse(options?.item ?? null);
  if (item) {
    form.inventory_user = item.inventory_user_name
    dataForm.inventory_user = item.inventory_user
    form.inventory_code = item.inventory_code
    form.inventory_name = item.inventory_name
    form.id = item.id
    form.audit = item.exception_status === 'EXCEPTION_STATUS'
    form.remark = item.remark
    dataForm.asset_class = item.asset_class
    item.inventory_rule.split(',').map(item => {
      switch (item) {
        case 'ALL_STAFF':
          form.all = true
          break
        case 'ALL_LOCATIONS':
          form.all_local = true
          break
        case 'MANUAL_ALLOWED':
          form.manual = true
          break
        case 'SURPLUS_ENABLED':
          form.open = true
          break
        case 'PHOTO_REQUIRED':
          form.upload = true
          break
      }
    })
  }
})

const showInventoryUser = ref(false)

const dateFilter = reactive({
  startDate: false,
  endDate: false
})

const filterList = reactive({
  assetClassList: [],
  assetDepartmentList: [],
  assetAddressList: [],
  assetAdminList: [],
  assetStatusList: []
})

const enumList = [
  {
    name: 'getViewTable', code: 'getAssetClassList', list: 'assetClassList', filters: [], field: 'asset_class'
  },
  {
    name: 'getViewTable',
    code: 'Sys_GetGroupNameById',
    list: 'assetDepartmentList',
    filters: [],
    field: 'asset_department'
  },
  {
    name: 'getViewTable', code: 'getAssetAddressList', list: 'assetAddressList', filters: [], field: 'asset_location'
  },
  {
    name: 'getViewTable', code: 'Sys_GetUserNameById', list: 'assetAdminList', filters: [], field: 'asset_admin'
  },
  {
    name: 'getBasicData',
    code: 'asset>status',
    list: 'assetStatusList',
    filters: [{name: 'group', value: 'B'}],
    field: 'asset_state'
  }
]

const confirm = (e, item) => {
  form[item.field] = e.value[0][item.text]
  dataForm[item.field] = e.value[0][item.value]
  item.show = false
}

const pickerData = ref([
  {
    type: 'assetClass',
    label: '资产分类',
    field: 'asset_class',
    show: false,
    click: (item) => item.show = true,
    key: 'asset_class_name',
    columns: 'assetClassList',
    confirm: confirm,
    text: 'asset_class_name',
    value: 'asset_class_code'
  },
  {
    type: 'assetDepartment',
    label: '使用部门',
    field: 'asset_department',
    show: false,
    click: (item) => item.show = true,
    key: 'text',
    columns: 'assetDepartmentList',
    confirm: confirm,
    text: 'text',
    value: 'id'
  },
  {
    type: 'assetUser',
    label: '使用人',
    field: 'asset_user',
    show: false,
    click: (item) => item.show = true,
    key: 'text',
    columns: 'assetAdminList',
    confirm: confirm,
    text: 'text',
    value: 'id'
  },
  {
    type: 'assetAddress',
    label: '存放位置',
    field: 'asset_location',
    show: false,
    click: (item) => item.show = true,
    key: 'asset_address_name',
    columns: 'assetAddressList',
    confirm: confirm,
    text: 'asset_address_name',
    value: 'asset_address_code'
  },
  {
    type: 'assetAdmin',
    label: '资产管理员',
    field: 'asset_admin',
    show: false,
    click: (item) => item.show = true,
    key: 'text',
    columns: 'assetAdminList',
    confirm: confirm,
    text: 'text',
    value: 'id'
  },
  {
    type: 'assetStatus',
    label: '资产状态',
    field: 'asset_state',
    show: false,
    click: (item) => item.show = true,
    key: 'text',
    columns: 'assetStatusList',
    confirm: confirm,
    text: 'text',
    value: 'id'
  }
])

const dataForm = reactive({
  inventory_code: '',
  inventory_user: '',
  asset_class: '',
  asset_department: '',
  asset_location: '',
  asset_admin: '',
  asset_state: '',
  asset_user: ''
})

const form = reactive({
  id:'',
  inventory_code: '',
  inventory_name: '',
  inventory_user: '',
  inventory_rule: '',
  all: false,
  all_local: false,
  manual: false,
  open: true,
  audit: false,
  upload: false,
  remark: '',
  asset_class: '',
  asset_department: '',
  asset_location: '',
  asset_user: '',
  asset_admin: '',
  asset_state: '',
  time: '',
  start_date: '',
  end_date: ''
})

const confirmDate = (e, name, field) => {
  dateFilter[name] = false
  form[field] = e[0]
}

const handlerDate = (name) => {
  dateFilter[name] = true
}

const handlerInventoryUser = () => {
  showInventoryUser.value = true
}

const confirmInventoryUser = (e) => {
  console.log(e)
  form.inventory_user = e.value[0].text
  dataForm.inventory_user = e.value[0].id
  showInventoryUser.value = false
}

const handlerCancel = () => {
  uni.navigateBack(-1)
}

const handlerSave = async () => {
  const filters = [
    {
      name: 'asset_class',
      value: dataForm.asset_class
    },
    {
      name: 'asset_admin',
      value: dataForm.asset_admin
    },
    {
      name: 'asset_state',
      value: dataForm.asset_state,
    },
    {
      name: 'asset_location',
      value: dataForm.asset_location
    },
    {
      name: 'asset_department',
      value: dataForm.asset_department
    },
    {
      name: 'start',
      value: form.start_date
    },
    {
      name: 'end',
      value: form.end_date
    }
  ]
  let params = {}

  const ruleEnum = []
  if (form.all) ruleEnum.push({
    name: '全员盘点',
    value: 'ALL_STAFF'
  })
  if (form.all_local) ruleEnum.push({
    name: '全位置盘点',
    value: 'ALL_LOCATIONS'
  })
  if (form.manual) ruleEnum.push({
    name: '允许手动盘点',
    value: 'MANUAL_ALLOWED'
  })
  if (form.open) ruleEnum.push({
    name: '开启盘盈',
    value: 'SURPLUS_ENABLED'
  })
  if (form.upload) ruleEnum.push({
    name: '要求拍照',
    value: 'PHOTO_REQUIRED'
  })

  params.inventory_rule = ruleEnum.map(item => item.value).join(',')
  params.inventory_type = ruleEnum.map(item => item.name).join(',')
  params.inventory_code = form.inventory_code
  params.inventory_name = form.inventory_name
  params.inventory_user = dataForm.inventory_user
  params.exception_status = form.audit ? 'EXCEPTION_STATUS' : null
  params.asset_class = dataForm.asset_class
  params.remark = form.remark
  params.id = form.id

  try {
    if (!params.inventory_name) {
      uni.showToast({
        title: '盘点名称不能为空',
        icon: 'none'
      })
      return
    }
    if (!params.inventory_user) {
      uni.showToast({
        title: '盘点人不能为空',
        icon: 'none'
      })
      return
    }
    if (!params.inventory_rule) {
      uni.showToast({
        title: '盘点规则不能为空',
        icon: 'none'
      })
      return
    }

    const resp = await request.post('/api/module/GetViewTable', {
      allColumnFilter: true,
      code: 'getAssetListIn',
      filters: filters,
      pageInput: {currentPage: 1, pageSize: 999},
      permissionKey: ''
    })
    let deptList = resp.isSuccess ? resp?.result?.viewTable ?? [] : []
    if (!deptList || deptList.length === 0) {
      uni.showToast({
        title: '没有符合盘点的资产',
        icon: 'none'
      })
      return
    }
    deptList = deptList.map((item) => ({
      asset_code: item.asset_code
    }))
    const res = await request.post('/api/module/Invoke', {
      pageCode: 'assetinventory',
      params: {
        args: [
          {
            name: 'interfaceCode',
            value: 'Assetinventory.doUpdateOne'
          },
          {
            name: 'model',
            value: params
          },
          {
            name: 'detLists',
            value: deptList
          }
        ]
      },
      methodName: 'doUpdateOne'
    })
    if (res.isSuccess) {
      uni.showToast({
        title: '保存成功',
        icon: 'success',
        complete: () => {
          uni.navigateBack({
            delta: 1,
            success: () => {
              uni.$emit('refresh-data')
            }
          })
        }
      })
      return
    }
    uni.showToast({
      title: '保存失败',
      icon: 'none'
    })
  } catch (e) {
    console.error(e)
  }
}

const requestData = async () => {
  const batchRequests = enumList.map(item => {
    const params = [{
      id: generateUUID(),
      service: 'Module',
      method: item.name,
      param: JSON.stringify({
        code: item.code,
        filters: item.filters
      })
    }]
    return request.post('/api/module/GetBatchResult', params).then(res => ({
      ...res,
      name: item.name,
      list: item.list
    }))
  }).filter(Boolean)
  try {
    const results = await Promise.all(batchRequests);
    results.forEach(({name, list, result, isSuccess, code}) => {
      if (!isSuccess || !code) return;
      if (name === 'getViewTable') {
        filterList[list] = result?.[0]?.response?.data?.viewTable ?? []
      } else if (name === 'getBasicData') {
        filterList[list] = result?.[0]?.response?.data?.data ?? []
      } else {
        filterList[list] = []
      }
    })
  } catch (e) {
    console.error(e)
  }
}

</script>

<style scoped lang="scss">

.border-bottom {
  border-bottom: 1px solid #f5f5f5;
}

.w100 {
  width: 100%;
}

.mla {
  margin-left: auto;
}

.add-page {
  width: 100%;
  padding-bottom: 140rpx;

  .form-container {
    margin: 20rpx;
    width: calc(100% - 40rpx);
    background-color: #fff;
    padding: 20rpx;

    > span {
      display: block;
      padding: 10rpx;
      font-size: .9rem;
      color: #509EFF;
    }
  }

  .footer-container {
    position: fixed;
    bottom: 0;
    left: 0;
    height: 130rpx;
    width: 100%;
    background-color: #509EFF;
    display: flex;
    align-items: center;
    justify-content: center;

    > :deep(.u-button.u-reset-button.u-button--info.u-button--square.u-button--normal.u-button--plain) {
      background-color: #509EFF;
      border: none;
      color: white;
      height: 100%;
    }
  }
}

</style>